<template>
  <div class="test-case-container p-4">
    <h2 class="mb-4">测试用例列表</h2>

    <!-- 测试用例表格 -->
    <el-table :data="cases" stripe border style="width: 100%" empty-text="暂无测试用例">
      <!-- 名称 -->
      <el-table-column prop="name" label="名称" width="180" />

      <!-- URL -->
      <el-table-column label="URL" min-width="200">
        <template #default="{ row }">
          <code class="url-code">{{ row.url }}</code>
        </template>
      </el-table-column>

      <!-- 方法 -->
      <el-table-column prop="method" label="方法" width="100">
        <template #default="{ row }">
          <el-tag :type="getMethodType(row.method)" size="small">
            {{ row.method }}
          </el-tag>
        </template>
      </el-table-column>

      <!-- 期望状态码 -->
      <el-table-column prop="expected_status" label="期望状态" width="120" />

      <!-- 操作 -->
      <el-table-column label="操作" width="300">
        <template #default="{ row }">
          <el-button size="small" @click="editCase(row)">编辑</el-button>
          <el-button size="small" type="success" @click="executeCase(row)">执行</el-button>
          <el-button size="small" type="warning" @click="openPerfDialog(row)">⚡ 压测</el-button>
          <el-button size="small" type="danger" @click="deleteTestCase(row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 压测配置弹窗 -->
    <TestDialog
      v-model="perfDialogVisible"
      :test-case="currentTestCase"
      @success="handleBenchmarkSuccess"
    />
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import api from '@/services/api'
import ReportDetailDialog from '@/components/ReportDetailDialog.vue'
import TestDialog from './TestDialog.vue'
import { useReportStore } from '@/stores/reportStore'

// 测试用例列表
const props = defineProps({
  cases: {
    type: Array,
    default: () => [],
  },
})

const emit = defineEmits(['handle_update'])

const reportStore = useReportStore()
// 获取方法标签颜色
const getMethodType = (method) => {
  switch (method?.toUpperCase()) {
    case 'GET':
      return 'success'
    case 'POST':
      return 'primary'
    case 'PUT':
      return 'warning'
    case 'DELETE':
      return 'danger'
    default:
      return 'info'
  }
}

// 编辑用例
const editCase = (item) => {
  // TODO: 跳转或弹出编辑表单
  console.log('编辑:', item)
  emit('handle_update', item)
}

// 执行测试用例
const executeCase = async (row) => {
  try {
    const res = await api.post(`test-cases/${row.id}/execute/`)
    // ✅ 保存到 Pinia
    reportStore.setFunctionalResult(res.data)
    ElMessage.success('功能测试完成')
  } catch (error) {
    ElMessage.error('执行失败')
  }
}

// 删除测试用例
const deleteTestCase = async (id) => {
  try {
    await ElMessageBox.confirm('确定删除该测试用例吗？', '警告', {
      confirmButtonText: '删除',
      cancelButtonText: '取消',
      type: 'warning',
    })
    await api.delete(`test-cases/${id}/`)
    cases.value = cases.value.filter((c) => c.id !== id)
    ElMessage.success('删除成功')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const perfDialogVisible = ref(false)
const currentTestCase = ref(null)

// 打开压测对话框
const openPerfDialog = (testCase) => {
  currentTestCase.value = testCase
  perfDialogVisible.value = true
}

const handleBenchmarkSuccess = async () => {
  try {
    const res = await api.get('/benchmark-reports/')
    console.log('res', res.data)
    // ✅ 保存到 Pinia
    reportStore.setBenchmarkResult(res.data)
    ElMessage.success('压测完成')
  } catch (err) {
    ElMessage.error('压测失败')
  }
}
</script>

<style scoped>
.test-case-container {
  max-width: 1200px;
  margin: 0 auto;
}

.url-code {
  font-family: 'Courier New', monospace;
  background: #f0f2f5;
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 13px;
}

.mt-6 {
  margin-top: 1.5rem;
}

.mb-4 {
  margin-bottom: 1rem;
}

.perf-form .form-group {
  margin-bottom: 16px;
}

.perf-form label {
  display: block;
  margin-bottom: 6px;
  font-weight: 500;
}
</style>
